package com.timo.flickr.model
{
	import com.timo.flickr.events.FlickrAPIEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	
	[Event( name="searchComplete", type="com.timo.flickr.events.FlickrAPIEvent")]
	[Event( name="getInfoComplete", type="com.timo.flickr.events.FlickrAPIEvent")]
	public class FlickrAPIProxy extends EventDispatcher{
		
		
		private const API_KEY:String = "b7e41161be466cc7bfc23909584e0bf4";
		private const API_URL:String = "http://api.flickr.com/services/rest/?";
		
		//http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=df82b98eb7448f5e63f23115e7856863&text=tiger&format=rest&auth_token=72157626705503319-0000000000000000&api_sig=e051e3934a6d0bdba04a8b894c39792f
		
		private var _flickrAPI:HTTPService = new HTTPService();
		
		
		public function FlickrAPIProxy(){
			_flickrAPI = new HTTPService();
			_flickrAPI.resultFormat = "xml";
			_flickrAPI.showBusyCursor = true;
			_flickrAPI.addEventListener( FaultEvent.FAULT, faultHandler );
		}
		
		
		public function search( text:String, page:int ):void{
			var url:String = API_URL + "method=flickr.photos.search&api_key=" + API_KEY + "&text=" + text + "&page=" + page;
			_flickrAPI.addEventListener( ResultEvent.RESULT, searchResultHandler );
			_flickrAPI.url = url;
			_flickrAPI.cancel();
			_flickrAPI.send();
		}
		
		
		public function getInfo( id:String, secret:String = null ):void{
			var url:String = API_URL + "method=flickr.photos.getInfo&api_key="+API_KEY+"&photo_id="+id+"&secret="+secret;
			_flickrAPI.addEventListener( ResultEvent.RESULT, getInfoHandler );
			_flickrAPI.url = url;
			_flickrAPI.cancel();
			_flickrAPI.send();
		}
		
		
		private function searchResultHandler( event:ResultEvent ):void{
			_flickrAPI.removeEventListener( ResultEvent.RESULT, searchResultHandler );
			dispatchEvent( new FlickrAPIEvent( FlickrAPIEvent.SEARCH_COMPLETE, new XML( event.result ) ) );
		}
		
		
		private function getInfoHandler( event:ResultEvent ):void{
			_flickrAPI.removeEventListener( ResultEvent.RESULT, getInfoHandler );
			dispatchEvent( new FlickrAPIEvent( FlickrAPIEvent.GET_INFO_COMPLETE, new XML( event.result ) ) );
		}
		
		
		private function  faultHandler( event:FaultEvent ):void{
			Alert.show( event.fault.faultDetail, "fault" );
		}
	}
}